<?php
namespace app\mini_api\controller;

class Driver extends Permission
{
    public function _initialize()
    {
        parent::_initialize();
        parent::check();
    }

    public function updatePhoto()
    {
        $this->user['photo'] = 'http://btsj.images.zrjt4000602666.com/'.$this->input_data['photo'];
        
        $data = [
            'realname' => trim($this->user['realname']),
            'id_card' => trim($this->user['id_card']), 
            'photo' => $this->_getBase64Img($this->user['photo']), 
        ];

        $result = action('common/AlicloudAuth/photoVerifyIdcard',$data);

        $res = $result->body;

        if($res->code != 200)
        {
            // $this->resErr('请上传本人照片');
            $this->resErr('错误提示：'.$res->message.$res->code);
            // $this->resErr('错误提示：'.$res->message.$res->code);
        }
        else
        {
            if($res->resultObject->passed == 'F') $this->resErr('请上传本人照片');
        }

        db('Driver')->update($this->user);
                
        $this->resSuc($this->user);
    }
    private function _getBase64Img($url){
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_BINARYTRANSFER, true);
        $image_data = curl_exec($ch);
        curl_close($ch);
        $image_base64 = base64_encode($image_data);

        return $image_base64;
    }
    // 学习拍照、签字
    public function createLeaningLog()
    {
        $data['photo'] = 'http://btsj.images.zrjt4000602666.com/'.$this->input_data['photo'];
        if($this->input_data['type'] == '拍照')
        {
            $imgs = [
                'imgA' => $this->_getBase64Img($data['photo']),
                'imgB' => $this->_getBase64Img($this->user['photo'])
            ];
            $result = action('common/AliFacebody/photoVerifyPhoto',$imgs);
            // $this->resErr($result);
            if($result->body->data->confidence < 50) $this->resErr('请本人拍照');
        }
        
        $data['driver_train_id'] = $this->input_data['driver_train_id'];
        $data['type'] = $this->input_data['type'];
        $data['create_time'] = time();
        db('DriverTrainLearningLog')->insert($data);

        // 如果是文档学习
        if($this->input_data['type'] == '签名') $this->_updateArticlePercent();
                
        $this->resSuc('ok');
    }

    private function _updateArticlePercent()
    {
        # 签名的课件属于文档 就设置学习进度为100
        $map = [
            'id' => $this->input_data['video_id']
        ];
        $video = db('Video')->where($map)->find();
        if($video['type'] == '文档'){
            $map = [
                'driver_train_id' => $this->input_data['driver_train_id'],
                'video_id' => $this->input_data['video_id']
            ];
            $data = [
                'percent' => 10000
            ];
            db('DriverTrainVideo')->where($map)->update($data);
        }
    }

    // 更新学习时间
    public function updateLeaningTime()
    {
        if($this->input_data['duration'] == 0) $this->resSuc('ok');
        $map = [
            'driver_train_id' => $this->input_data['driver_train_id'],
            'video_id' => $this->input_data['video_id']
        ];
        $dtv = db('DriverTrainVideo')->where($map)->find();
        $dtv['duration_done'] = $this->input_data['duration'];

        # 计算完成百分比
        $dtv['percent'] = bcdiv($this->input_data['duration'],$dtv['duration'],4) * 10000 ;

        db('DriverTrainVideo')->update($dtv);

        # 更新司机的培训计划完成时间和完成百分比
        $this->_updateDriverTrainPercent($this->input_data['driver_train_id']);
                
        $this->resSuc('ok');
    }

    private function _updateDriverTrainPercent($driverTrainId)
    {
        $durationDone = 0; // 整个学习计划完成的秒数
        $duration = 0; // 整个学习计划的秒数

        $map = [
            'driver_train_id' => $driverTrainId
        ];

        $videos = db('DriverTrainVideo')->where($map)->select();
        foreach ($videos as $v) {
            $durationDone += $v['duration_done'];
            $duration += $v['duration'];
        }

        $map = [
            'id' => $driverTrainId
        ];
        $data = [
            'percent' => bcdiv( $durationDone,$duration,4 ) * 10000,
            'duration_done' => $durationDone
        ];

        db('DriverTrain')->where($map)->update($data);
    }

    // 验证是否为本人
    public function validatePhoto()
    {
        $this->resSuc('ok');
    }

    public function getById()
    {
        $map['id'] = $this->input_data['id'];
        $result = db('Driver')->where($map)->find();

        $this->resSuc($result);
    }

    public function getInfo()
    {
        $this->resSuc($this->user);
    }

    // 答案提交
    public function updateExamResponse()
    {
        $response = json_decode($this->input_data['answerList'],true);

        foreach ($response as $v) {
            unset($v['type']);
            db('DriverExamQuestion')->update($v);
        }

        # 更新考试用时
        $map = [
            'id' => $this->input_data['id']
        ];
        $data = [
            'duration' => $this->input_data['duration'],
            'status' => 1
        ];
        db('DriverExam')->where($map)->update($data);

        $score = $this->_getExamScore();
                
        $this->resSuc('ok');
    }

    // 算分
    private function _getExamScore()
    {
        $map = [
            'driver_exam_id' => $this->input_data['id']
        ];
        $rows = db('DriverExamQuestion')->alias('a')->join('question b','a.question_id = b.id','LEFT')->field('a.*,b.result AS daan')->where($map)->select();

        $quantity = count($rows); // 题目数量
        $scoreOfOne = bcdiv(100,$quantity);
        $totalScore = 0;

        foreach ($rows as $v) {
            if($v['answer'] == $v['daan'])
            {
                $totalScore += $scoreOfOne;
                db('DriverExamQuestion')->where(['id'=>$v['id']])->update(['score'=>$scoreOfOne]);
            }
        }

        $map = [
            'id' => $this->input_data['id']
        ];
        $data = [
            'score' => $totalScore,
            'status' => 1
        ];
        db('DriverExam')->where($map)->update($data);

    }


}
